package com.it.system.gatewayservice.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.it.system.educommonapi.entity.User;
import com.it.system.educommonapi.util.JwtUtils;
import com.it.system.educommonapi.util.RsaUtils;
import com.it.system.gatewayservice.config.WhiteListConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;


import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.io.UnsupportedEncodingException;
import java.util.List;

@Slf4j
public class LoginAuthenticationFilter implements GlobalFilter, Ordered {

    //白名单
    @Autowired
    private WhiteListConfig whiteListConfig;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获得请求和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //对白名单放行
        List<String> whiteList = (List<String>) whiteListConfig.getWhiteList();
        for (String url : whiteList) {
            String path = request.getURI().getPath();
            if (path.contains(url)) {
                log.info("白名单放行：" + path);
                //放行请求
                return chain.filter(exchange);
            }
        }
        //获得请求头
        String token = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
        //解析token
        try {
            // 如果token以"Bearer "开头，则去掉这个前缀
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            
            String user = JwtUtils.getUsernameFromToken(token, RsaUtils.publicKey);
            log.info("用户：" + user);
            return chain.filter(exchange);
        } catch (Exception e) {
            log.error("token解析失败,token={}",token,e);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            DataBuffer data = response.bufferFactory().wrap("token解析失败".getBytes());
            return response.writeWith(Mono.just(data));
        }
    }

    /**
     * Get the order value of this object.
     * <p>Higher values are interpreted as lower priority. As a consequence,
     * the object with the lowest value has the highest priority (somewhat
     * analogous to Servlet {@code load-on-startup} values).
     * <p>Same order values will result in arbitrary sort positions for the
     * affected objects.
     *
     * @return the order value
     * @see #HIGHEST_PRECEDENCE
     * @see #LOWEST_PRECEDENCE
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
